﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Medical.Business;
using System.IO;
using Medical.Entity;
using System.Collections.Generic;

/// <summary>
/// 文章信息操作页
/// </summary>
public partial class DoArticle : AdminPage
{
    /// <summary>
    /// ID
    /// </summary>
    protected int nID;

    /// <summary>
    /// 文章类型
    /// </summary>
    protected ArticelTypeEnum eType;

    /// <summary>
    /// 操作类型
    /// </summary>
    protected string strType = string.Empty;

    /// <summary>
    /// 分类级别
    /// </summary>
    protected int nSortCount = 0;

    protected int nPartType = 0;

    /// <summary>
    /// 图片大小
    /// </summary>
    protected string strImgSize = string.Empty;

    protected string strImgPix = string.Empty;

    /// <summary>
    /// 页面初始化
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        strType = Common.GetQueryValue("type", 0);
        nPartType = Convert.ToInt32(Common.GetQueryValue("parttype", 0));
        eType = (ArticelTypeEnum)Convert.ToInt32(Common.GetQueryValue("infotype", 0));
        nSortCount = Convert.ToInt32(Common.GetQueryValue("count", 0));
        //ddlSort.Items.Add(new ListItem("未分类", ""));
        strImgSize = WebConfigInfo.FileSize < 1024 * 1024 ? (WebConfigInfo.FileSize / 1024 + "K") : (WebConfigInfo.FileSize / (1024 * 1024) + "M");
        if (strType == "edit")
        {
            //获取ID
            nID = Convert.ToInt32(Common.GetQueryValue("id", 0));
        }
        switch (eType)
        {
            case ArticelTypeEnum.Expert:
                ImgDiv.Visible = true;
                ltlTitle.Text = "姓名";
                break;
            case ArticelTypeEnum.Case:
                ImgDiv.Visible = true;
                break;
            case ArticelTypeEnum.Equipment:
                ImgDiv.Visible = true;
                break;
            case ArticelTypeEnum.Subject:
                ImgDiv.Visible = true;
                break;
            case ArticelTypeEnum.About:
                pagetitle.Visible = false;
                pagekeywords.Visible = false;
                pagedes.Visible = false;
                break;
        }

        if (!Page.IsPostBack)
        {
            InitSort();
            //页面数据初始化
            InitData();
        }

    }

    /// <summary>
    /// 初始化分类下拉框
    /// </summary>
    protected void InitSort()
    {
        BisSortInfo bisSortInfo = new BisSortInfo();
        //绑定分类下拉框
        DataTable dtSortList = bisSortInfo.GetAllSortList((ArticelTypeEnum)eType);
        if (dtSortList != null && dtSortList.Rows.Count > 0)
        {
            int nSortIndex = 0;
            foreach (DataRow dr in dtSortList.Rows)
            {
                nSortIndex = Convert.ToInt32(dr["SortIndex"]);
                if (nSortIndex == 1 && (eType == ArticelTypeEnum.News|| eType==ArticelTypeEnum.Health))
                    continue;
                ddlSort.Items.Add(new ListItem(Common.GetSortIcon(nSortIndex) + dr["Name"].ToString(), dr["ID"].ToString()));
            }
            dtSortList.Dispose();
        }
    }

    /// <summary>
    /// 页面数据初始化
    /// </summary>
    protected void InitData()
    {
        if (strType == "edit")
        {
            //获取文章信息
            Article Info = new BisArticle().Get(nID);
            if (Info != null)
            {
                if (nAdminFeatures != 1)
                {
                    if (Info.AdminID != nAdminUserID)
                    {
                        Response.Write("没有权限！");
                        Response.End();
                    }
                }
                txtTitle.Text = Info.Name;
                if (eType == ArticelTypeEnum.Subject)
                {
                    txtInfo.Text = Info.Info;
                }
                else
                {
                    fckInfo.Value = Info.Info;
                }
                ddlSort.SelectedValue = Info.SortID.ToString();
                hfImg.Value = Info.ImgPlace;
                txtPageUrlName.Text = Info.PageUrlName;
                txtPageTitle.Text = Info.PageTitle;
                txtPageKeywords.Text = Info.PageKeywords;
                txtPageDescription.Text = Info.PageDescription;
                txtSubTitle.Text = Info.SubTitle;
                switch (eType)
                {
                    case ArticelTypeEnum.Expert:
                    case ArticelTypeEnum.Case:
                    case ArticelTypeEnum.Equipment:
                    case ArticelTypeEnum.Subject:
                        ImgPanel.Visible = true;
                        imgAdver.ImageUrl = "~/" + WebConfigInfo.FilePlace + "d/" + Info.ImgPlace;
                        break;
                    case ArticelTypeEnum.About:
                        if (Info.SubTitle == "联系我们")
                        {
                            pagetitle.Visible = true;
                            pagekeywords.Visible = true;
                            pagedes.Visible = true;
                        }
                        break;

                }
            }
            DataTable dtArticelMate = new BisArticleMetaValue().GetList(eType, nID);
            rptArticleMeta.DataSource = dtArticelMate;
            rptArticleMeta.DataBind();
        }
        else
        {
            DataTable dtArticelMate = new BisArticleMeta().GetList(eType);
            dtArticelMate.Columns.Add("ID", typeof(System.Int32));
            dtArticelMate.Columns.Add("MetaValue", typeof(System.String));
            rptArticleMeta.DataSource = dtArticelMate;
            rptArticleMeta.DataBind();
        }


    }

    /// <summary>
    /// 提交
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        bool result = false;
        BisArticle bisArticle = new BisArticle();
        Article Info = new Article();
        Info.Name = txtTitle.Text.Trim();
        Info.AdminID = nAdminUserID;
        if (eType == ArticelTypeEnum.Subject)
        {
            Info.Info = txtInfo.Text.Trim();
        }
        else
        {
            Info.Info = fckInfo.Value.Trim();
        }
        Info.Type = (int)eType;
        Info.PageUrlName = txtPageUrlName.Text.Trim();
        Info.PageTitle = txtPageTitle.Text.Trim();
        Info.PageKeywords = txtPageKeywords.Text.Trim();
        Info.PageDescription = txtPageDescription.Text.Trim();
        Info.SubTitle = txtSubTitle.Text.Trim();
        //if (eType == ArticelTypeEnum.Technology)
        //{
        //    Info.PartType = Convert.ToInt32(ddlPartType.SelectedValue);
        //}
        string strImg = string.Empty;
        if (ddlSort.SelectedValue != string.Empty)
            Info.SortID = Convert.ToInt32(ddlSort.SelectedValue);

        if (eType == ArticelTypeEnum.Expert || eType == ArticelTypeEnum.Case || eType == ArticelTypeEnum.Equipment || eType == ArticelTypeEnum.Subject)
        {
            //上传图片
            if (fuImg.HasFile)
            {
                result = UpImg(fuImg, ref strImg);
                if (!result)
                    return;
            }
            else if (strType == "add")
            {
                Until.Alert("请选择要上传的图片！");
                return;
            }
        }

        if (strType == "add")
        {
            //新增信息
            Info.ImgPlace = strImg;
            nID = bisArticle.InsertArticle(Info);
            result = nID > 0;
        }
        else if (strType == "edit")
        {
            Info.ImgPlace = (strImg == string.Empty ? hfImg.Value : strImg);
            Info.ID = nID;
            result = bisArticle.Update(Info);
            if (eType == ArticelTypeEnum.Expert || eType == ArticelTypeEnum.Case || eType == ArticelTypeEnum.Equipment || eType == ArticelTypeEnum.Subject)
            {
                if (result && !string.IsNullOrEmpty(strImg))
                    Until.DeleteFile(Server.MapPath("~/" + WebConfigInfo.FilePlace + "d/" + hfImg.Value));
            }
        }
        //结果处理
        if (result)
        {
            if (rptArticleMeta.Items.Count > 0)
            {
                List<int> IDList = new List<int>();
                List<int> MetaIDList = new List<int>();
                List<string> ValueList = new List<string>();
                foreach (RepeaterItem rptItem in rptArticleMeta.Items)
                {
                    int nTemID = 0;
                    HiddenField hfID = (HiddenField)rptItem.FindControl("hfID");
                    int.TryParse(hfID.Value, out nTemID);
                    IDList.Add(nTemID);
                    HiddenField hfArticleMetaID = (HiddenField)rptItem.FindControl("hfArticleMetaID");
                    int.TryParse(hfArticleMetaID.Value, out nTemID);
                    MetaIDList.Add(nTemID);
                    TextBox txtInfo = (TextBox)rptItem.FindControl("txtInfo");
                    ValueList.Add(txtInfo.Text.Trim());
                }
                new BisArticleMetaValue().SetMetaValue(nID, IDList, MetaIDList, ValueList);
            }
            Until.AlertJS("提交成功！", "ResetPage();");
        }
        else
        {
            Until.Alert("提交失败！");
        }
    }

    /// <summary>
    /// 上传图片
    /// </summary>
    /// <param name="fileImg"></param>
    /// <param name="strImg"></param>
    /// <returns></returns>
    protected bool UpImg(FileUpload fileImg, ref string strImg)
    {
        string strExtension = Path.GetExtension(fileImg.FileName).ToLower();
        if (fileImg.PostedFile.ContentLength > WebConfigInfo.FileSize)
        {
            Until.Alert("图片大小不超过" + strImgSize + "！");
            return false;
        }
        //验证图片格式
        if (Until.CheckFileType(0, strExtension))
        {
            string strFileName = Guid.NewGuid().ToString().Replace("-", "") + strExtension;
            string strYear = DateTime.Now.Year.ToString();
            string strMonth = DateTime.Now.Month.ToString();

            //原图
            string strFile = Server.MapPath("~/" + WebConfigInfo.FilePlace + "/d/" + strYear + "/" + strMonth+"/");
            if (!Directory.Exists(strFile))
            {
                Directory.CreateDirectory(strFile);
            }
            fileImg.SaveAs(strFile + strFileName);

            ////小图
            //string[] strSmallSize = WebConfigInfo.CaseSmallImg.Split('*');
            //System.Drawing.Image SmallImage = Common.MakeMiImage(fileImg.PostedFile, Convert.ToInt32(strSmallSize[0]), Convert.ToInt32(strSmallSize[1]));
            //strFile = Server.MapPath("~/" + WebConfigInfo.FilePlace + "/s/" + strYear + "/");
            //if (!Directory.Exists(strFile))
            //{
            //    Directory.CreateDirectory(strFile);
            //}
            //SmallImage.Save(strFile + strFileName);
            //SmallImage.Dispose();

            strImg = strYear + "/" + strMonth+"/"+ strFileName;
            return true;
        }
        else
        {
            Until.Alert("图片格式不正确！");
            return false;
        }
    }

    /// <summary>
    /// 是否显示
    /// </summary>
    /// <returns></returns>
    protected string CheckDisplay()
    {
        switch (eType)
        {
            case ArticelTypeEnum.Subject:
                return "display:none";
        }
        return "";
    }

    /// <summary>
    /// 是否显示
    /// </summary>
    /// <returns></returns>
    protected string CheckDisplay1()
    {
        switch (eType)
        {
            case ArticelTypeEnum.Subject:
                return "";
        }
        return "display:none";
    }
}
